package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.service.CartService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;


public class UpdateCartAjaxServlet extends HttpServlet {

    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";

    private Iterator<CartItem> cartItems;
    private Cart cart;
    private String itemIdString;
    private CartItem cartItem;
    private int localQuatity;


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        cart = (Cart) session.getAttribute("cart");
        Account account = (Account)session.getAttribute("account");

        for(int i = 0; i < cart.getCartItemList().size();i++){
            cartItem = cart.getCartItemList().get(i);
            itemIdString = cartItem.getItem().getItemId();
            localQuatity = Integer.valueOf(request.getParameter(itemIdString));
            cartItem.setQuantity(localQuatity);
        }
        CartService cartService = new CartService();
        cartService.updateCartByUserId(account.getUsername(),cart);
        System.out.print(account.getUsername());
        session.setAttribute("cart", cart);
        String str = cart.getSubTotal().toString();

        response.setContentType("text/plain");//相应类型为字符串；
        PrintWriter out = response.getWriter();

        out.print(str);
        out.flush();
        out.close();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
